package com.javaee.wordtree.controller;


import com.javaee.wordtree.common.Result;
import com.javaee.wordtree.sdk.weixin.MessageTextEntity;
import com.javaee.wordtree.sdk.weixin.SignatureUtil;
import com.javaee.wordtree.sdk.weixin.XmlUtil;
import com.javaee.wordtree.service.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @Date 2025/5/23 19:51
 * @Author liuyang2004
 * @Description
 */
@Slf4j
@RestController()
@CrossOrigin("*")
@RequestMapping("/weixin/portal/")
public class WeixinController {

    @Value("${weixin.config.originalid}")
    private String originalid;
    @Value("${weixin.config.token}")
    private String token;
    @Resource
    private WeixinService weixinService;


    @GetMapping(value = "receive", produces = "text/plain;charset=utf-8")
    public String validate(@RequestParam(value = "signature", required = false) String signature,
                           @RequestParam(value = "timestamp", required = false) String timestamp,
                           @RequestParam(value = "nonce", required = false) String nonce,
                           @RequestParam(value = "echostr", required = false) String echostr) {
        try {
            log.info("微信公众号验签信息开始 [{}, {}, {}, {}]", signature, timestamp, nonce, echostr);
            if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
                throw new IllegalArgumentException("请求参数非法，请核实!");
            }
            boolean check = SignatureUtil.check(token, signature, timestamp, nonce);
            log.info("微信公众号验签信息完成 check：{}", check);
            if (!check) {
                return null;
            }
            return echostr;
        } catch (Exception e) {
            log.error("微信公众号验签信息失败 [{}, {}, {}, {}]", signature, timestamp, nonce, echostr, e);
            return null;
        }
    }

    @PostMapping(value = "receive", produces = "application/xml; charset=UTF-8")
    public String post(@RequestBody String requestBody,
                       @RequestParam("signature") String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce,
                       @RequestParam("openid") String openid,
                       @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {
        try {
            log.info("接收微信公众号信息请求{}开始 {}", openid, requestBody);
            // 使用DOM4J解析XML，替代XStream
            org.dom4j.io.SAXReader reader = new org.dom4j.io.SAXReader();
            org.dom4j.Document document = reader.read(new java.io.StringReader(requestBody));
            org.dom4j.Element root = document.getRootElement();

            // 手动创建并设置对象
            MessageTextEntity message = new MessageTextEntity();
            message.setToUserName(getElementText(root, "ToUserName"));
            message.setFromUserName(getElementText(root, "FromUserName"));
            message.setCreateTime(getElementText(root, "CreateTime"));
            message.setMsgType(getElementText(root, "MsgType"));
            message.setEvent(getElementText(root, "Event"));
            message.setContent(getElementText(root, "Content"));
            message.setMsgId(getElementText(root, "MsgId"));
            message.setEventKey(getElementText(root, "EventKey"));
            message.setTicket(getElementText(root, "Ticket"));


            if ("event".equals(message.getMsgType()) && "SCAN".equals(message.getEvent())) {

                return buildMessageTextEntity(openid, "欢迎来到词境星云");
            }

            // 处理文本消息
            if ("text".equals(message.getMsgType()) && message.getContent() != null) {
                String content = message.getContent();
                // 检查是否符合"查询用户：xxx"格式
                if (content.startsWith("查询用户：")) {
                    // 提取用户名称
                    String userName = content.substring("查询用户：".length());
                    // 回复"正在查询xxx"
                    return buildMessageTextEntity(openid, "正在查询" + userName);
                }
            }


            return buildMessageTextEntity(openid, "你好，" + message.getContent());
        } catch (Exception e) {
            log.error("接收微信公众号信息请求{}失败 {}", openid, requestBody, e);
            return "";
        }
    }

    private String buildMessageTextEntity(String openid, String content) {
        MessageTextEntity res = new MessageTextEntity();
        // 公众号分配的ID
        res.setFromUserName(originalid);
        res.setToUserName(openid);
        res.setCreateTime(String.valueOf(System.currentTimeMillis() / 1000L));
        res.setMsgType("text");
        res.setContent(content);
        return XmlUtil.beanToXml(res);
    }

    /**
     * 获取XML元素的文本内容
     * @param root 根元素
     * @param elementName 元素名称
     * @return 元素文本内容，如果元素不存在则返回null
     */
    private String getElementText(org.dom4j.Element root, String elementName) {
        org.dom4j.Element element = root.element(elementName);
        return element != null ? element.getText() : null;
    }


    @RequestMapping(value = "qrcode_ticket", method = RequestMethod.GET)
    public Result<String> weixinQrCodeTicket() {
        try {
            String qrCodeTicket = weixinService.createQrCodeTicket();
            String qrCodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+qrCodeTicket;
            log.info("生成微信扫码 ticket:{}", qrCodeTicket);
            return Result.<String>builder()
                    .code("0000")
                    .msg("调用成功")
                    .data(qrCodeUrl)
                    .build();
        } catch (Exception e) {
            log.error("生成微信扫码 ticket 失败", e);
            return Result.<String>builder()
                    .code("0001")
                    .msg("调用失败")
                    .build();
        }
    }

}